<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
    <link href="./static/bootstrap.min.css" rel="stylesheet">
    <link href="./static/toastr.min.css" rel="stylesheet">

    <script src="./static/jquery-3.1.1.min.js"></script>
    <script src="./static/bootstrap.min.js"></script>
    <script src="./static/toastr.min.js"></script>
    <script src="./static/vue.min.js"></script>
    <style>
        #page-wrapper {
            margin-left: 0
        }

        [v-cloak] {
            display: none;
        }

        .mb {
            margin-bottom: 30px;
        }

        ul {
            height: 10rem;
            overflow: scroll;
            padding: 1rem;
            border: 1px solid #dc3545;
            border-radius: 5px;
            box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, .25);
        }

        ul::-webkit-scrollbar {
            display: none;
        }

        ul li {
            list-style: none;
        }

        li.you {
            text-align: right;
        }

        select {
            min-width: 100px;
            padding: 5px;
        }

        .bold {
            font-weight: bold;
        }
    </style>
</head>
<body>

<div id="wrapper" v-cloak>
    <div id="page-wrapper" class="gray-bg">
        <div class="col-sm-4 col-sm-offset-4"><h3 class="m-t-none m-b">聊天信息</h3>
            <form role="form" class="mb">
                <div class="form-group">
                    <label>我的ID</label>
                    <input type="text" id="user_id" v-model="from_" class="form-control" placeholder="请输入用户ID">
                </div>
                <div>
                    <button class="btn btn-block btn-sm btn-danger mb" type="button" @click="init()">Sign In</button>
                </div>
                <div class="form-group">
                    <input type="text" id="friend" v-model="to_" class="form-control" placeholder="对方ID">
                </div>
                <div class="form-group">
                    <input type="text" placeholder="请输入..." id="message" class="form-control" @keydown.ctrl="sendMsg()">
                </div>
                <div>
                    <button class="btn btn-block btn-sm btn-primary" type="button" @click="sendMsg()"><strong> Send </strong></button>
                    <button class="btn btn-block btn-sm btn-warning" type="button" @click="show=!show"><strong> 隐藏聊天框 </strong></button>
                </div>
            </form>
            <div class="" v-show="show">
                <div>聊天记录</div>
                <ul>
                    <li v-for="(vo,index) in msg" :class="vo.__from == from_?'me':'you'" v-html="vo.msg"></li>
                </ul>
                <div>对方列表</div>
                <select :size="list.length" v-model="current" @change="change_to()">
                    <option :value="index" v-for="(vo,index) in list" :class="{bold:vo.is_online}">{{vo.user}}</option>
                </select>
            </div>
        </div>
    </div>
</div>

<script>
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-full-width",
        showMethod: 'slideDown',
        timeOut: 1500
    };

    let socket, wsServer = 'ws://igccc.com:9501';

    Vue.filter('time', function (value) {
        return new Date(parseInt(value) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
    });

    var vm = new Vue({
        el: '#wrapper',
        data: {
            msg: [],
            from_: 'user-120',
            to_: 'seller-1',
            list: [],
            current: 0,
            show: true
        },
        methods: {
            sendMsg(type) {
                if (!type) type = 'send_msg';
                let param = {
                    type: type,
                    to: vm.to_,
                    from: vm.from_,
                    msg: document.getElementById('message').value
                };
                if (type == 'send_msg' && param.msg == '') {
                    toastr.error('发送内容不能为空!~');
                    return;
                }
                if (type == 'send_msg' && param.msg.length > 2000) {
                    toastr.error('消息内容不得超过2000字符!~');
                    return;
                }
                if (param.from == param.to) {
                    toastr.warning('无法给自已发信息哦~!');
                    return;
                }
                socket.send(JSON.stringify(param));
            },
            init() {
                socket = new WebSocket(wsServer, this.from_);
                socket.onopen = (evt) => {
                    toastr.success("已连接...");
                };
                socket.onclose = (evt) => {
                    toastr.error("远程连接断开...");
                };
                socket.onmessage = evt => {
                    let res = JSON.parse(evt.data);
                    if (res.status == 'success') {
                        switch (res.type) {
                            case 'init':
                                //TODO 所有聊天对象列表
                                if (res.data.length) {
                                    vm.list = res.data;
                                    vm.msg = res.data[0].msg_history;
                                }
                                break;
                            case 'get_msg':
                                vm.msg = res.data;
                                break;
                            case 'online_notice':
                            case 'offline_user':
                                vm.list.forEach(function (v, i) {
                                    if (v.user == res.data) {
                                        vm.list[i].is_online = !vm.list[i].is_online;
                                    }
                                });
                                break;
                            case 'send_msg':
                                vm.msg = [res.data].concat(vm.msg);
                                if (!vm.show) {
                                    toastr.success('您有新消息,请打开聊天面板');
                                }
                                break;
                        }
                    } else {
                        toastr.error(res.msg);
                    }
                };
                socket.onerror = (evt, e) => {
                    console.log(evt);
                    console.log(e);
                    this.current = null;
                    toastr.error('错误：' + evt.data);
                };
                window.onbeforeunload = function (e) {
                    e = e || window.event;
                    if (e) {
                        sessionStorage.setItem('you', 1);
                    }
                };
            },
            change_to() {
                this.to_ = this.list[this.current].user;
                this.sendMsg('get_msg');
            },

        },
        created() {
            let flag = sessionStorage.getItem('you');
            if (flag) {
                // this.init();//刷新页面重新连接
            }
        }
    });


</script>
</body>
</html>